<!DOCTYPE html>
<html>
  <!-- meta/link... -->
  



<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <!-- Global site tag (gtag.js) - Google Analytics -->


  <title>Nginx 从安装到高可用，一篇搞定！ | 张不胖</title>

  <link rel="icon" type="image/x-icon, image/vnd.microsoft.icon" href="/favicon.ico">
  <link rel="stylesheet" href="https://at.alicdn.com/t/font_1911880_c1nvbyezg17.css">
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  
    <script>
        var themeModelId = '';
        if (themeModelId) {
            localStorage.setItem('modelId', themeModelId);
        }
    </script>
    
    <script src="https://cdn.jsdelivr.net/gh/yuang01/live2d-widget@latest/autoload.js"></script>
    <script>
        var live2dOpen = eval('true') || false;
        if (!live2dOpen) {
            localStorage.setItem('waifu-display', 1609323474481);
        }
    </script>
  
  
  
<link rel="stylesheet" href="/css/animate.min.css">

  
<link rel="stylesheet" href="/css/style.css">

  
  
    
<link rel="stylesheet" href="/js/fancybox/jquery.fancybox.min.css">

  
  
    
<link rel="stylesheet" href="/js/shareJs/share.min.css">

  
  <style>
        @media (max-width: 992px) {
            #waifu {
                display: none;
            }
        }
    </style>
    <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
    <link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">

    

    <!-- import link -->
    
        
            
        
            
        
    
    <!-- import script -->
    
        
            <script src="/js/calendar.js"></script>
        
            <script src="/js/languages.js"></script>
        
            
        
            
        
    

<meta name="generator" content="Hexo 6.3.0"><link rel="alternate" href="/atom.xml" title="张不胖" type="application/atom+xml">
</head>

  
  <!-- 依赖于jquery和vue -->
  <script src="/js/jquery3.5.1.js"></script>
  <script src="/js/vue2.6.11.js"></script>
  
  <body>
    <!-- 预加载动画 -->
    <!-- 页面预加载动画 -->

    
    <!-- 判断是否为暗黑风格 -->
    <!-- 判断是否为黑夜模式 -->
<script>
  let isDark = JSON.parse(localStorage.getItem('dark')) || JSON.parse('false');

  if (isDark) {
    $(document.body).addClass('darkModel');
  }
</script>

    <!-- 头部导航等 -->
    
<header class="header " id="navHeader"
  style="position: fixed;
  left: 0; top: 0; z-index: 10;width: 100%;"
>
  <div class="header-content">
    <div class="bars">
      <div id="appDrawer" class="sidebar-image">
  <div class="drawer-box-icon">
    <i class="fa fa-bars" aria-hidden="true" @click="showDialogDrawer"></i>
  </div>
  
  <transition name="fade">
    <div class="drawer-box_mask" v-cloak style="display: none;" v-show="visible" @click.self="cancelDialogDrawer">
    </div>
  </transition>
  <div class="drawer-box" :class="{'active': visible}">
    <div class="drawer-box-head bg-color">
      <img class="drawer-box-head_logo" src="/medias/logo.png" alt="logo">
      <h3 class="drawer-box-head_title">张不胖</h3>
      <h5 class="drawer-box-head_desc"></h5>
    </div>
    
    <div class="drawer-box-content">
      <ul class="drawer-box-content_menu">
        
          
            <li class="drawer-box-content_item" style="position: relative;">
              
                <a href="/" class="drawer-menu-item-link">
                  
                    <i class="fa fa-home" aria-hidden="true"></i>
                  
                  <span class="name">首页</span>
                </a>
              
            </li>
          
            <li class="drawer-box-content_item" style="position: relative;">
              
                <a href="/musics" class="drawer-menu-item-link">
                  
                    <i class="fa fa-music" aria-hidden="true"></i>
                  
                  <span class="name">音乐</span>
                </a>
              
            </li>
          
            <li class="drawer-box-content_item" style="position: relative;">
              
                <a href="/archives" class="drawer-menu-item-link">
                  
                    <i class="fa fa-archive" aria-hidden="true"></i>
                  
                  <span class="name">归档</span>
                </a>
              
            </li>
          
            <li class="drawer-box-content_item" style="position: relative;">
              
                <a href="/tags" class="drawer-menu-item-link">
                  
                    <i class="fa fa-tags" aria-hidden="true"></i>
                  
                  <span class="name">标签</span>
                </a>
              
            </li>
          
            <li class="drawer-box-content_item" style="position: relative;">
              
                <a href="/categories" class="drawer-menu-item-link">
                  
                    <i class="fa fa-bookmark" aria-hidden="true"></i>
                  
                  <span class="name">分类</span>
                </a>
              
            </li>
          
            <li class="drawer-box-content_item" style="position: relative;">
              
                <a href="/about" class="drawer-menu-item-link">
                  
                    <i class="fa fa-user" aria-hidden="true"></i>
                  
                  <span class="name">关于</span>
                </a>
              
            </li>
          
            <li class="drawer-box-content_item" style="position: relative;">
              
                <a href="/friends" class="drawer-menu-item-link">
                  
                  <span class="name">友情链接</span>
                </a>
              
            </li>
          
            <li class="drawer-box-content_item" style="position: relative;">
              
                <a href="javascript:;" class="drawer-menu-item-link has-children" @click="openOrCloseMenu(7)">
                  <span>
                    
                      <i class="fa fa-link"></i>
                    
                    <span class="name">更多</span>
                  </span>
                  <i class="fa fa-chevron-left arrow " :class="{'icon-rotate': isOpen(7)}" aria-hidden="true"></i>
                </a>
                <ul class="drawer-sub-menu" v-if="isOpen(7)">
                  
                  <li>
                    <a href="/gallery">
                      
                      <i class="fa fa-music" style="margin-top: -20px;"></i>
                      
                      <span>图库</span>
                    </a>
                  </li>
                  
                  <li>
                    <a target="_blank" rel="noopener" href="http://baidu.com">
                      
                      <i class="fa fa-film" style="margin-top: -20px;"></i>
                      
                      <span>百度</span>
                    </a>
                  </li>
                  
                </ul>
              
            </li>
          
        
        
          <li class="drawer-box-content_item">
            <a target="_blank" rel="noopener" href="https://github.com/zhangcun1113/hexo-theme-bamboo">
              <i class="fa fa-github" aria-hidden="true"></i>
              <span>Github</span>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</div>

<script>
  var body = document.body || document.documentElement || window;
  var vm = new Vue({
    el: '#appDrawer',
    data: {
      visible: false,
      top: 0,
      openArr: [],
    },
    computed: {
    },
    mounted() {
    },
    methods: {
      isOpen(index) {
        if (this.openArr.includes(index)) {
          return true;
        } else {
          return false;
        }
      },
      openOrCloseMenu(curIndex) {
        const index = this.openArr.indexOf(curIndex);
        if (index !== -1) {
          this.openArr.splice(index, 1);
        } else {
          this.openArr.push(curIndex);
        }
      },
      showDialogDrawer() {
        this.visible = true;
        // 防止页面滚动，只能让弹框滚动
        this.top = $(document).scrollTop()
        body.style.cssText = 'width: 100%; height: 100%;overflow: hidden;';
      },
      cancelDialogDrawer() {
        this.visible = false;
        body.removeAttribute('style');
        $(document).scrollTop(this.top)
      }
    },
    created() {}
  })
</script>

    </div>
    <div class="blog-title" id="author-avatar">
      
        <div class="avatar">
          <img src="/medias/logo.png" alt="logo">
        </div>
      
      <a href="/" class="logo">张不胖</a>
    </div>
    <nav class="navbar">
      <ul class="menu">
        
          
            <li class="menu-item" style="position: relative;">
              
                <a href="/" class="menu-item-link" title="首页">
                  
                    <i class="fa fa-home" aria-hidden="true"></i>
                  
                  <span class="name">首页</span>
                </a>
              
            </li>
          
            <li class="menu-item" style="position: relative;">
              
                <a href="/musics" class="menu-item-link" title="音乐">
                  
                    <i class="fa fa-music" aria-hidden="true"></i>
                  
                  <span class="name">音乐</span>
                </a>
              
            </li>
          
            <li class="menu-item" style="position: relative;">
              
                <a href="/archives" class="menu-item-link" title="归档">
                  
                    <i class="fa fa-archive" aria-hidden="true"></i>
                  
                  <span class="name">归档</span>
                </a>
              
            </li>
          
            <li class="menu-item" style="position: relative;">
              
                <a href="/tags" class="menu-item-link" title="标签">
                  
                    <i class="fa fa-tags" aria-hidden="true"></i>
                  
                  <span class="name">标签</span>
                </a>
              
            </li>
          
            <li class="menu-item" style="position: relative;">
              
                <a href="/categories" class="menu-item-link" title="分类">
                  
                    <i class="fa fa-bookmark" aria-hidden="true"></i>
                  
                  <span class="name">分类</span>
                </a>
              
            </li>
          
            <li class="menu-item" style="position: relative;">
              
                <a href="/about" class="menu-item-link" title="关于">
                  
                    <i class="fa fa-user" aria-hidden="true"></i>
                  
                  <span class="name">关于</span>
                </a>
              
            </li>
          
            <li class="menu-item" style="position: relative;">
              
                <a href="/friends" class="menu-item-link" title="友情链接">
                  
                  <span class="name">友情链接</span>
                </a>
              
            </li>
          
            <li class="menu-item" style="position: relative;">
              
                <a href="javascript:;" class="menu-item-link" title="更多">
                  
                    <i class="fa fa-link"></i>
                  
                  <span class="name">更多</span>
                  <i class="fa fa-chevron-down arrow" aria-hidden="true"></i>
                </a>
                <ul class="sub-menu">
                  
                  <li>
                    <a href="/gallery">
                      
                      <i class="fa fa-music" style="margin-top: -20px;"></i>
                      
                      <span>图库</span>
                    </a>
                  </li>
                  
                  <li>
                    <a target="_blank" rel="noopener" href="http://baidu.com">
                      
                      <i class="fa fa-film" style="margin-top: -20px;"></i>
                      
                      <span>百度</span>
                    </a>
                  </li>
                  
                </ul>
              
            </li>
          
        
      </ul>
      
      
        <div id="appSearch">
  <div class="search"  @click="showDialog()"><i class="fa fa-search" aria-hidden="true"></i></div>
  <transition name="fade">
    <div class="message-box_wrapper" style="display: none;" v-cloak v-show="dialogVisible" @click.self="cancelDialogVisible()">
      <div class="message-box animated bounceInDown">
        <!-- <div class="close" style="overflow: hidden;">
          <i class="fa fa-close" aria-hidden="true" style="float:right;" @click.self="cancelDialogVisible()"></i>
        </div> -->
        <h2>
          <span>
            <i class="fa fa-search" aria-hidden="true"></i>
            <span class="title">本地搜索</span>
          </span>
          <i class="fa fa-close close" pointer style="float:right;" aria-hidden="true" @click.self="cancelDialogVisible()"></i>
        </h2>
        <form class="site-search-form">
          <input type="text"
            placeholder="请输入关键字"
            id="local-search-input" 
            @click="getSearchFile()"
            class="st-search-input"
            v-model="searchInput"
          />
        </form>
        <div class="result-wrapper">
          <div id="local-search-result" class="local-search-result-cls"></div>
        </div>
      </div>
    </div>
  </transition>
</div>
<script src="/js/local_search.js"></script>
<script>
  var body = document.body || document.documentElement || window;
  var vm = new Vue({
    el: '#appSearch',
    data: {
      dialogVisible: false,
      searchInput: '',
      top: 0,
    },
    computed: {
    },
    mounted() {
    },
    methods: {
      showDialog() {
        this.dialogVisible = true;
        // 防止页面滚动，只能让弹框滚动
        this.top = $(document).scrollTop()
        body.style.cssText = 'overflow: hidden;';
      },
      getSearchFile() {
        if (!this.searchInput) {
          getSearchFile("/search.xml");
        }
      },
      cancelDialogVisible() {
        this.dialogVisible = false;
        body.removeAttribute('style');
        $(document).scrollTop(this.top)
      },
    },
    created() {}
  })
</script>
<!-- 解决刷新页面闪烁问题，可以在元素上添加display: none, 或者用vue.extend方法，详情：https://blog.csdn.net/qq_31393401/article/details/81017912 -->
<!-- 下面是搜索基本写法 -->
<!-- <script type="text/javascript" id="local.search.active">
  var inputArea = document.querySelector("#local-search-input");
  inputArea.onclick   = function(){ getSearchFile(); this.onclick = null }
  inputArea.onkeydown = function(){ if(event.keyCode == 13) return false }
</script> -->

      

    </nav>
  </div>
  
    <a target="_blank" rel="noopener" href="https://github.com/zhangcun1113/hexo-theme-bamboo" class="github-corner color-primary" aria-label="View source on GitHub"><svg width="60" height="60" viewBox="0 0 250 250" style="fill:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
  
  
    <div id="he-plugin-simple"></div>
    <script>
      WIDGET = {
        CONFIG: {
          "modules": "012",
          "background": 5,
          "tmpColor": "4A4A4A",
          "tmpSize": 16,
          "cityColor": "4A4A4A",
          "citySize": 16,
          "aqiSize": 16,
          "weatherIconSize": 24,
          "alertIconSize": 18,
          "padding": "10px 10px 10px 10px",
          "shadow": "1",
          "language": "auto",
          "borderRadius": 5,
          "fixed": "false",
          "vertical": "middle",
          "horizontal": "center",
          "key": "2784dd3fcb1e4f0f9a9b579bf69641f2"
        }
      }
    </script>
    <script src="https://widget.qweather.net/simple/static/js/he-simple-common.js?v=2.0"></script> 
    

    <!-- 当头部导航设置为背景透明的时候  -->
    
      <script src="/js/header/index.js" data-pjax></script>
    
</header>

    <!-- 需要在上面加载的js -->
    <script>
    function loadScript(src, cb) {
        setTimeout(function () {
            var HEAD = document.getElementsByTagName('head')[0] || document.documentElement;
            var script = document.createElement('script');
            script.setAttribute('type', 'text/javascript');
            if (cb) script.onload = cb;
            script.setAttribute('src', src);
            HEAD.appendChild(script);
        });
    }

    //https://github.com/filamentgroup/loadCSS
    var loadCSS = function (href, before, media, attributes) {
        var doc = window.document;
        var ss = doc.createElement("link");
        var ref;
        if (before) {
            ref = before;
        }
        else {
            var refs = (doc.body || doc.getElementsByTagName("head")[0]).childNodes;
            ref = refs[refs.length - 1];
        }
        var sheets = doc.styleSheets;
        if (attributes) {
            for (var attributeName in attributes) {
                if (attributes.hasOwnProperty(attributeName)) {
                    ss.setAttribute(attributeName, attributes[attributeName]);
                }
            }
        }
        ss.rel = "stylesheet";
        ss.href = href;
        ss.media = "only x";
        function ready(cb) {
            if (doc.body) {
                return cb();
            }
            setTimeout(function () {
                ready(cb);
            });
        }
        ready(function () {
            ref.parentNode.insertBefore(ss, (before ? ref : ref.nextSibling));
        });
        var onloadcssdefined = function (cb) {
            var resolvedHref = ss.href;
            var i = sheets.length;
            while (i--) {
                if (sheets[i].href === resolvedHref) {
                    return cb();
                }
            }
            setTimeout(function () {
                onloadcssdefined(cb);
            });
        };
        function loadCB() {
            if (ss.addEventListener) {
                ss.removeEventListener("load", loadCB);
            }
            ss.media = media || "all";
        }
        if (ss.addEventListener) {
            ss.addEventListener("load", loadCB);
        }
        ss.onloadcssdefined = onloadcssdefined;
        onloadcssdefined(loadCB);
        return ss;
    };
    
</script>
 

<!-- 轮播图所需要的js -->
<script src="/js/swiper/swiper.min.js"></script>
<script src="/js/swiper/vue-awesome-swiper.js"></script>
<script src="/js/swiper/swiper.animate1.0.3.min.js"></script>


  <script src="/js/vue-typed-js/index.js"></script>


<!-- 首页的公告滚动插件的js需要重新加载 -->
<script src="/js/vue-seamless-scroll/index.js"></script>

<!-- 打字机效果js -->
<script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11"></script>


    <!-- 内容区域 -->
    <div id="safearea">
      <main class="main" id="pjax-container" style="margin-top: 0;">
        
 <!-- prismjs 代码高亮 -->
 
    
    <link href="/js/prism/prism-line-numbers.css" rel="stylesheet">
    
        <link href="/js/prism/prism.min.css" rel="stylesheet">
    

    <style>
        pre[class*="language-"] {
            overflow-y: hidden;
        }
        .line-numbers .line-numbers-rows {
            border: none;
        }
    </style>
  


<div class="bg-dark-floor" style="position: fixed;left: 0;top: 0;width: 100%;height: 100%;z-index: -1;"></div>

<!-- 文章详情页顶部图片和标题 -->




<div class="post-detail-header lazyload" id="thumbnail_canvas" data-original="/medias/3.jpg" style="background-repeat: no-repeat; background-size: cover; 
  background-position: center center;position: relative;">
  <div class="post-detail-header-mask"></div>
  <canvas id="header_canvas"style="position:absolute;bottom:0;pointer-events:none;"></canvas>
  
  <div class="post-detail-header_info-box">
    <div class="title-box">
      <span class="title">
        Nginx 从安装到高可用，一篇搞定！
      </span>
    </div>
    
    
      
        <span class="post-detail-header_date">
          <i class="fa fa-calendar"></i> 发表于：2022-12-06 |
        </span>
      

      

      
        <div class="post-detail-header_wordcount">
          <span class="totalcount">
            <i class="fa fa-file-text-o"></i> 字数统计: 5.2k |
          </span>
  
          <span class="min2read">
            <i class="fa fa-clock-o"></i> 阅读时长: 22分钟 |
          </span>
  
          
            <span class="reading">
              <i class="fa fa-eye"></i> 阅读量：<span id="busuanzi_value_page_pv"></span>
            </span>
          
        </div>
      
    
  </div>
  
  
    <script src="/js/bubble/bubble.js"></script>
  
</div>



<div class="row justify-position">
  <div class="main-content">
    <article class="post post-detail">
      
      <div class="post-content">
        <p>一、Nginx安装</p>
<p>二、配置反向代理</p>
<p>三、配置负载均衡</p>
<p>四、upstream指令参数</p>
<p>五、配置ssl证书提供https访问</p>
<p>六、配置ha nginx</p>
<p>七、LVS（Linux Virtual Server）实现高可用负载均衡</p>
<p>附：LVS的负载均衡算法</p>
<p>八、搭建Keepalived+Lvs+Nginx高可用集群负载均衡 </p>
<pre><code>一、Nginx安装
1、去官网http://nginx.org/下载对应的nginx包，推荐使用稳定版本
2、上传nginx到linux系统
3、安装依赖环境
(1)安装gcc环境

yum install gcc-c++

(2)安装PCRE库，用于解析正则表达式

yum install -y pcre pcre-devel

(3)zlib压缩和解压缩依赖

yum install -y zlib zlib-devel

(4)SSL 安全的加密的套接字协议层，用于HTTP安全传输，也就是https

yum install -y openssl openssl-devel

4、解压，需要注意，解压后得到的是源码，源码需要编译后才能安装
tar -zxvf nginx-1.16.1.tar.gz

5、编译之前，先创建nginx临时目录，如果不创建，在启动nginx的过程中会报错
mkdir /var/temp/nginx -p

6、在nginx目录，输入如下命令进行配置，目的是为了创建makefile文件
./configure \   
--prefix=/usr/local/nginx \    
--pid-path=/var/run/nginx/nginx.pid \    
--lock-path=/var/lock/nginx.lock \    
--error-log-path=/var/log/nginx/error.log \    
--http-log-path=/var/log/nginx/access.log \    
--with-http_gzip_static_module \    
--http-client-body-temp-path=/var/temp/nginx/client \    
--http-proxy-temp-path=/var/temp/nginx/proxy \    
--http-fastcgi-temp-path=/var/temp/nginx/fastcgi \    
--http-uwsgi-temp-path=/var/temp/nginx/uwsgi \    
--http-scgi-temp-path=/var/temp/nginx/scgi

注：代表在命令行中换行，用于提高可读性配置命令：


7、make编译&amp;安装
make
make install

8、进入sbin目录启动nginx
启动：nginx停止：./nginx -s stop重新加载：./nginx -s reload

“
推荐下自己做的 Spring Boot 的实战项目：

https://github.com/YunaiV/ruoyi-vue-pro

二、配置反向代理
1、配置upstream

upstream [proxyName] &#123;
    server 192.168.1.173:8080;
    server 192.168.1.174:8080;
    server 192.168.1.175:8080;
&#125;

2、配置server

server &#123;
    listem  80;
    server_name www.tomcats.com;

    location / &#123;
        proxy_pass http://tomcats;
    &#125;
&#125;

“
推荐下自己做的 Spring Cloud 的实战项目：

https://github.com/YunaiV/onemall

三、配置负载均衡
nginx默认采用轮训的方式进行负载均衡

1、使用加权轮询

upstream [proxyName] &#123;
    server 192.168.1.173:8080 weight=1;
    server 192.168.1.174:8080 weight=5;
    server 192.168.1.175:8080 weight=2;
&#125;

2、hash负载均衡

upstream [proxyName] &#123;
    ip_hash

    server 192.168.1.173:8080;
    server 192.168.1.174:8080;
    server 192.168.1.175:8080;
&#125;

hash算法实际上只会计算 192.168.1这段做哈希

使用ip_hash的注意点：

不能把后台服务器直接移除，只能标记down.

3、url hash负载均衡

upstream [proxyName] &#123;
    hash $request_url;

    server 192.168.1.173:8080;
    server 192.168.1.174:8080;
    server 192.168.1.175:8080;
&#125;

4、最小连接负载均衡

upstream [proxyName] &#123;
    least_conn;

    server 192.168.1.173:8080;
    server 192.168.1.174:8080;
    server 192.168.1.175:8080;
&#125;

四、upstream指令参数
max_conns：限制最大同时连接数 1.11.5之前只能用于商业版

slow_start：单位秒，权重在指定时间内从1上升到指定值，不适用与hash负载均衡、随机负载均衡 如果在 upstream 中只有一台 server，则该参数失效（商业版才有）

down：禁止访问

backup：备用机 只有在其他服务器无法访问的时候才能访问到 不适用与hash负载均衡、随机负载均衡

max_fails：表示失败几次，则标记server已宕机，剔出上游服务 默认值1

fail_timeout：表示失败的重试时间 默认值10

1、keepalived

upstream [proxyName] &#123;
    server 192.168.1.173:8080 weight=1;
    server 192.168.1.174:8080 weight=5;
    server 192.168.1.175:8080 weight=2;

    keepalive 32; #保持的连接数
&#125;

server &#123;
    listem  80;
    server_name www.tomcats.com;

    location / &#123;
        proxy_pass http://tomcats;
        proxy_http_version 1.1; #连接的协议版本
        proxy_set_header Connection &quot;&quot;; 清空连接请求头
    &#125;
&#125;

2、控制浏览器缓存

server &#123;
    listem  80;
    server_name www.tomcats.com;

    location / &#123;
        proxy_pass http://tomcats;
               expires 10s;  #浏览器缓存10秒钟
               #expires @22h30m  #在晚上10点30的时候过期
               #expires -1h  #缓存在一小时前时效
               #expires epoch  #不设置缓存
               #expires off  #缓存关闭，浏览器自己控制缓存
               #expires max  #最大过期时间
    &#125;
&#125;

3、反向代理缓存

upstream [proxyName] &#123;
    server 192.168.1.173:8080 weight=1;
    server 192.168.1.174:8080 weight=5;
    server 192.168.1.175:8080 weight=2;
&#125;

#proxy_cache_path 设置缓存保存的目录的位置
#keys_zone设置共享内以及占用的空间大小
#mas_size 设置缓存最大空间
#inactive 缓存过期时间，错过此时间自动清理
#use_temp_path 关闭零时目录
proxy_cache_path /usr/local/nginx/upsteam_cache keys_zone=mycache:5m max_size=1g inactive=8h use_temp_path=off;

server &#123;
    listem  80;
    server_name www.tomcats.com;
    #开启并使用缓存
    proxy_cache mycache;
    #针对200和304响应码的缓存过期时间
    proxy_cache_valid 200 304 8h;   

    location / &#123;
        proxy_pass http://tomcats;
    &#125;
&#125;

五、配置ssl证书提供https访问
1. 安装SSL模块
要在nginx中配置https，就必须安装ssl模块，也就是: http_ssl_module。

进入到nginx的解压目录：/home/software/nginx-1.16.1

新增ssl模块(原来的那些模块需要保留)

./configure \
--prefix=/usr/local/nginx \
--pid-path=/var/run/nginx/nginx.pid \
--lock-path=/var/lock/nginx.lock \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--with-http_gzip_static_module \
--http-client-body-temp-path=/var/temp/nginx/client \
--http-proxy-temp-path=/var/temp/nginx/proxy \
--http-fastcgi-temp-path=/var/temp/nginx/fastcgi \
--http-uwsgi-temp-path=/var/temp/nginx/uwsgi \
--http-scgi-temp-path=/var/temp/nginx/scgi  \
--with-http_ssl_module

编译和安装

makemake install

2、配置HTTPS
把ssl证书 *.crt 和 私钥 *.key 拷贝到/usr/local/nginx/conf目录中。

新增 server 监听 443 端口：

server &#123;
    listen       443;
    server_name  www.imoocdsp.com;
    # 开启ssl
    ssl     on;
    # 配置ssl证书
    ssl_certificate      1_www.imoocdsp.com_bundle.crt;
    # 配置证书秘钥
    ssl_certificate_key  2_www.imoocdsp.com.key;
    # ssl会话cache
    ssl_session_cache    shared:SSL:1m;
    # ssl会话超时时间
    ssl_session_timeout  5m;
    # 配置加密套件，写法遵循 openssl 标准
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    ssl_prefer_server_ciphers on;
    
    location / &#123;
        proxy_pass http://tomcats/;
        index  index.html index.htm;
    &#125;
&#125;

六、配置ha nginx
1、安装keepalived
(1)下载

https://www.keepalived.org/download.html

(2)解压

tar -zxvf keepalived-2.0.18.tar.gz

(3)使用configure命令配置安装目录与核心配置文件所在位置：

./configure --prefix=/usr/local/keepalived --sysconf=/etc

prefix ：keepalived安装的位置sysconf：keepalived核心配置文件所在位置，固定位置，改成其他位置则keepalived启动不了，/var/log/messages中会报错

sysconf ：keepalived核心配置文件所在位置，固定位置，改成其他位置则keepalived启动不了，/var/log/messages中会报错

配置过程中可能会出现警告信息，如下所示：

*** WARNING - this build will not support IPVS with IPv6. Please install libnl/libnl-3 dev libraries to support IPv6 with IPVS.

# 安装libnl/libnl-3依赖
yum -y install libnl libnl-devel  

(4)安装keepalived

make &amp;&amp; make install

(5)配置文件 在/etc/keepalived/keepalived.conf

(6)忘记安装配置的目录，则通过如下命令找到：

whereis keepalived

(7)启动keepalived

进入sbin目录

./keepalived

2、配置keepalived 主机
(1)通过命令 vim keepalived.conf 打开配置文件

global_defs &#123; 
    # 路由id：当前安装keepalived的节点主机标识符，保证全局唯一 
    router_id keep_171 
&#125; 

vrrp_instance VI_1 &#123; 
    # 表示状态是MASTER主机还是备用机BACKUP 
    state MASTER 
    # 该实例绑定的网卡 
    interface ens33 
    # 保证主备节点一致即可 
    virtual_router_id 51 
    # 权重，master权重一般高于backup，如果有多个，那就是选举，谁的权重高，谁就当选 
    priority 100 
    # 主备之间同步检查时间间隔，单位秒 
    advert_int 2 
    # 认证权限密码，防止非法节点进入 
    authentication &#123; 
        auth_type PASS 
        auth_pass 1111 
    &#125; 
    # 虚拟出来的ip，可以有多个（vip） 
    virtual_ipaddress &#123; 
        192.168.1.161 
    &#125;
&#125;

附：查看网卡信息命令

ip addr

(2)启动keepalived

(3)查看进程

ps -ef|grep keepalived

(4)查看vip(虚拟ip)

在网卡ens33下，多了一个192.168.1.161，这个就是虚拟ip

3、把keepalived注册为系统服务
(1)拷贝配置文件

将keepalived目录下etc/init.d/keepalived拷贝到/etc/init.d/下

将keepalived目录下etc/sysconfig/keepalived拷贝到/etc/sysconfig/下

(2)刷新systemctl

systemctl daemon-reload

(3)启动、停止、重启keepalived

#启动
systemctl start keepalived.service
#停止
systemctl stop keepalived.service
#重启
systemctl restart keepalived.service

4、实现双机主备高可用



(1)修改备机配置

global_defs &#123; 
    router_id keep_172 
&#125; 
vrrp_instance VI_1 &#123; 
    # 备用机设置为BACKUP 
    state BACKUP 
    interface ens33 
    virtual_router_id 51 
    # 权重低于MASTER 
    priority 80 
    advert_int 2 
    authentication &#123; 
        auth_type PASS auth_pass 1111 
    &#125;
    virtual_ipaddress &#123;
        # 注意：主备两台的vip都是一样的，绑定到同一个vip
        192.168.1.161 
    &#125; 
&#125;

(2) 启动 Keepalived

(3) 访问vip即可访问主机，当主机失效时访问vip就会访问到备机

5、keepalived配置nginx自动重启
(1)编写脚本

在/etc/keepalived/下创建脚本check_nginx_alive_or_not

#!/bin/bash 

A=`ps -C nginx --no-header |wc -l` 
# 判断nginx是否宕机，如果宕机了，尝试重启 
if [ $A -eq 0 ];then 
    /usr/local/nginx/sbin/nginx 
    # 等待一小会再次检查nginx，如果没有启动成功，则停止keepalived，使其启动备用机 
    sleep 3 
        if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then 
            killall keepalived 
        fi 
fi

(2)添加运行权限

chmod +x /etc/keepalived/check_nginx_alive_or_not.sh

(3)配置keepalived监听nginx脚本

vrrp_script check_nginx_alive &#123; 
    script &quot;/etc/keepalived/check_nginx_alive_or_not.sh&quot; 
    interval 2 # 每隔两秒运行上一行脚本 
    weight 10 # 如果脚本运行失败，则升级权重+10 
&#125;

(4)在vrrp_instance中新增监控的脚本

track_script &#123; 
    check_nginx_alive # 追踪 nginx 脚本
&#125;

(5)重启Keepalived使得配置文件生效

systemctl restart keepalived

6、keepalived双主热备
(1)配置DNS轮询

在同一个域名下配置两个ip，自行百度

(2)配置第一台主机

global_defs &#123;
    router_id keep_171 
&#125; 
vrrp_instance VI_1 &#123; 
    state MASTER i
    nterface ens33 
    virtual_router_id 51 
    priority 100 
    advert_int 1 
    authentication &#123; 
        auth_type PASS 
        auth_pass 1111 
    &#125; 
    virtual_ipaddress &#123; 
        192.168.1.161 
    &#125; 
&#125; 

vrrp_instance VI_2  &#123;
    state BACKUP 
    interface ens33 
    virtual_router_id 52 
    priority 80 
    advert_int 1 
    authentication &#123; 
        auth_type PASS 
        auth_pass 1111 
    &#125; 
    virtual_ipaddress &#123; 
        192.168.1.162 
    &#125;
&#125;

(3)配置第二台主机

global_defs &#123;
    router_id keep_172 
&#125; 
vrrp_instance VI_1 &#123; 
    state BACKUP 
    interface ens33 
    virtual_router_id 51 
    priority 80 
    advert_int 1 
    authentication &#123; 
        auth_type PASS 
        auth_pass 1111 
    &#125; 
    virtual_ipaddress &#123; 
        192.168.1.161
    &#125;
&#125; 

vrrp_instance VI_2 &#123;
    state MASTER 
    interface ens33 
    virtual_router_id 52 
    priority 100 
    advert_int 1 
    authentication &#123; 
        auth_type PASS 
        auth_pass 1111 
    &#125; 
    virtual_ipaddress &#123; 
        192.168.1.162 
    &#125;
&#125;

(4)重启两台Keepalived

systemctl restart keepalived

七、LVS（Linux Virtual Server）实现高可用负载均衡
1、为什么要使用LVS+Nginx
lvs基于四层负载均衡，工作效率较Nginx的七层负载更高，使用LVS搭建Nginx集群，可以提高性能

四层负载均衡无法对信息处理，只能通过ip+端口的形式转发，所以需要七成负载进行数据的处理

Nginx接收请求来回，LVS可以只接受不响应

2、LVS的三种模式
(1)NAT模式

客户端将请求发往LVS，LVS会选择一台服务器响应请求，服务器将结果返回给LVS，LVS再返回给客户端。

在NAT模式中，服务器的网关必须指向LVS，否则报文无法送达客户端

NAT 技术将请求的报文和响应的报文都需要通过LVS进行地址改写，因此网站访问量比较大的时候负载均衡调度器有比较大的瓶颈，一般要求最多之能 10-20 台节点

NAT 模式支持对 IP 地址和端口进行转换。即用户请求的端口和真实服务器的端口可以不一致

(2)TUN模式

客户端将请求发往LVS，LVS会选择一台服务器响应请求，在客户端与服务器之间建立隧道，返回结果的时候直接由服务器返回响应，不在经过LVS。

TUN模式必须所有的服务器上都绑定VIP的IP地址，所有的服务器都必须有网卡。

TUN模式走隧道运维难度大，并且会直接暴露服务器地址

服务器将应答包直接发给用户。所以，减少了负载均衡器的大量数据流动，负载均衡器不再是系统的瓶颈，就能处理很巨大的请求量，这种方式，一台负载均衡器能够为很多服务器进行分发。而且跑在公网上就能进行不同地域的分发

(3)DR模式

客户端将请求发往LVS，LVS会选择一台服务器响应请求，返回结果的时候通过统一的路由进行返回，不在经过LVS。

和TUN模式一样，LVS只是分发请求，应答包通过单独的路由返回给客户端，与TUN相比这种方式不需要隧道结构，可以兼容大多数的操作系统，同时统一路由可以隐藏真实的物理服务器。DR模式效率更高，但配置更复杂.

所有服务器节点和LVS只能在一个局域网里面。

3、搭建LVS-DR模式
先关闭掉服务器上网络配置管理器，避免网络接口冲突

systemctl stop NetworkManagersystemctl disable NetworkManager

(1)创建子接口（创建LVS的虚拟ip）

进入网卡配置目录/etc/sysconfig/network-scripts/,找到网卡配置文件，这里以ifcfg-ens33为例，拷贝并创建子接口

cp ifcfg-ens33 ifcfg-ens33:1

修改子接口配置如下

配置中的 192.168.1.150 就是vip，是提供给外网用户访问的ip地址

DEVICE=&quot;ens33:1&quot;ONBOOT=&quot;yes&quot;IPADDR=192.168.1.150NETMASK=255.255.255.0BOOTPROTO=static

重启网络服务

service network restart

重启成功后，ip addr 查看一下，你会发现多了一个ip，也就是虚拟ip（vip）

“
注意：阿里云不支持配置网卡，需要购买相应的负载均衡服务，腾讯云支持配置网卡，但需要购买网卡支持，一个网卡支持10个虚拟ip配置

(2)安装ipvsadm

如今的centos都集成了LVS，所以ipvs是自带的，我们只需要安装ipvsadm即可（ipvsadm是管理集群的工具，通过ipvs可以管理集群，查看集群等操作）

yum install ipvsadm

(3)配置服务器（RS）的虚拟ip

进入网卡配置目录/etc/sysconfig/network-scripts/,找到ifcfg-lo，拷贝并创建子接口

cp ifcfg-lo ifcfg-lo:1

修改子接口配置如下

DEVICE=&quot;lo:1&quot;
IPADDR=192.168.1.150
NETMASK=255.255.255.255
NETWORK=127.0.0.0
BROADCAST=127.255.255.255
ONBOOT=&quot;yes&quot;
NAME=loopback

重启网络服务成功后，ip addr 查看一下，你会发现多了一个ip，也就是虚拟ip（vip）

(4)为服务器（RS）配置arp

ARP响应级别与通告行为参数说明

arp-ignore：ARP响应级别（处理请求）
    0：只要本机配置了ip，就能响应请求
    1：请求的目标地址到达对应的网络接口，才会响应请求
arp-announce：ARP通告行为（返回响应）
    0：本机上任何网络接口都向外通告，所有的网卡都能接受到通告
    1：尽可能避免本网卡与不匹配的目标进行通告2：只在本网卡通告

打开sysctl.conf:

vim /etc/sysctl.conf

配置所有网卡、默认网卡以及虚拟网卡的arp响应级别和通告行为，分别对应：all，default，lo

# configration for lvs 
net.ipv4.conf.all.arp_ignore = 1 
net.ipv4.conf.default.arp_ignore = 1 
net.ipv4.conf.lo.arp_ignore = 1 

net.ipv4.conf.all.arp_announce = 2 
net.ipv4.conf.default.arp_announce = 2 
net.ipv4.conf.lo.arp_announce = 2

刷新配置文件

sysctl -p

增加一个网关，用于接收数据报文，当有请求到本机后，会交给lo去处理

route add -host 192.168.1.150 dev lo:1

将网关添加至开机启动

echo &quot;route add -host 192.168.1.150 dev lo:1&quot; &gt;&gt; /etc/rc.local

(4)使用ipvsadm配置集群规则

创建LVS节点，用户访问的集群调度者

ipvsadm -A -t 192.168.1.150:80 -s rr -p 5

-A：添加集群

-t：tcp协议ip地址：设定集群的访问

ip：也就是LVS的虚拟ip

-s：设置负载均衡的算法，

rr：表示轮询

-p：设置连接持久化的时间,在指定时间内同一个用户的请求会访问到同一个服务器中

创建多台RS真实服务器

ipvsadm -a -t 192.168.1.150:80 -r 192.168.1.171:80 -g 
ipvsadm -a -t 192.168.1.150:80 -r 192.168.1.172:80 -g

-a：添加真实服务器

-t：tcp协议

-r：真实服务器的ip地址

-g：设定DR模式

保存到规则库，否则重启失效

ipvsadm -S

检查集群

#查看集群列表
ipvsadm -Ln
#查看集群状态
ipvsadm -Ln --stats

一些其他命令

 # 重启ipvsadm，重启后需要重新配置 
 service ipvsadm restart 
 # 查看持久化连接 
 ipvsadm -Ln --persistent-conn 
 # 查看连接请求过期时间以及请求源ip和目标ip 
 ipvsadm -Lnc 
 # 设置tcp tcpfin udp 的过期时间（一般保持默认） 
 ipvsadm --set 1 1 1 
 # 查看过期时间 
 ipvsadm -Ln --timeout

(5)访问虚拟ip，完成LVS搭建

附：LVS的负载均衡算法
(1)静态算法
静态：根据LVS本身自由的固定的算法分发用户请求。

轮询（Round Robin 简写’rr’）：轮询算法假设所有的服务器处理请求的能力都一样的，调度器会把所有的请求平均分配给每个真实服务器。（同Nginx的轮询）

加权轮询（Weight Round Robin 简写’wrr’）：安装权重比例分配用户请求。权重越高，被分配到处理的请求越多。（同Nginx的权重）

源地址散列（Source Hash 简写’sh’）：同一个用户ip的请求，会由同一个RS来处理。（同Nginx的ip_hash）

目标地址散列（Destination Hash 简写’dh’）：根据url的不同，请求到不同的RS。（同Nginx的url_hash）

(2)动态算法
动态：会根据流量的不同，或者服务器的压力不同来分配用户请求，这是动态计算的。

最小连接数（Least Connections 简写’lc’）：把新的连接请求分配到当前连接数最小的服务器。

加权最少连接数（Weight Least Connections 简写’wlc’）：服务器的处理性能用数值来代表，权重越大处理的请求越多。Real Server 有可能会存在性能上的差异，wlc动态获取不同服务器的负载状况，把请求分发到性能好并且比较空闲的服务器。

最短期望延迟（Shortest Expected Delay 简写’sed’）：特殊的wlc算法。举例阐述，假设有ABC三台服务器，权重分别为1、2、3 。如果使用wlc算法的话，当一个新请求进来，它可能会分给ABC中的任意一个。使用sed算法后会进行如下运算：



A：（1+1）/1=2

B：（1+2）/2=3/2

C：（1+3）/3=4/3

最终结果，会把这个请求交给得出运算结果最小的服务器。最少队列调度（Never Queue 简写’nq’）：永不使用队列。如果有Real Server的连接数等于0，则直接把这个请求分配过去，不需要在排队等待运算了（sed运算）。

八、搭建Keepalived+Lvs+Nginx高可用集群负载均衡
如果原先服务器上配置了LVS+nginx需要清空ipvsadm中的配置

ipvsadm -C

如果配置了Keepalived+Nginx双主集群也需要去除掉Keepalived中原先的配置，按照的后文进行配置

(1)使用keepalived配置Master LVS
在LVS的机器上安装keepalived，安装过程参考上文

(1)修改keepalived的配置

global_defs &#123;
    router_id keep_151 
&#125; 
vrrp_instance VI_1 &#123; 
    state MASTER 
    interface ens33 
    virtual_router_id 41 
    priority 100 
    advert_int 1 
    authentication &#123; 
        auth_type PASS 
        auth_pass 1111 
    &#125; 
    virtual_ipaddress &#123; 
        192.168.1.150
    &#125;
&#125; 

#配置集群访问的ip+端口，端口和nginx保持一致
virtual_server 192.168.1.150 80&#123;
    #健康检查的时间，单位：秒
    delay_loop 6
    #配置负载均衡的算法，默认的轮询
    lb_algo rr
    #设置LVS的模式 NAT|TUN|DR
    lb-kind DR
    #设置会话持久化的时间
    persistence_timeout 5
    #协议
    protocol TCP
    
    #配置负载均衡的真实服务器，也就是nginx节点的具体的ip地址
    real_server 192.168.1.171 80&#123;
        #轮询权重配比
        weight 1
        #设置健康检查
        TCP_CHECK &#123;
            #检查80端口
            connect_port 80
            #超时时间
            connect_timeout 2
            #重试次数
            nb_get_retry 2
            #重试间隔时间
            delay_before_retry 3
        &#125;
    &#125;
    real_server 192.168.1.171 80&#123;
        weight 1
        TCP_CHECK &#123;
            connect_port 80
            connect_timeout 2
            nb_get_retry 2
            delay_before_retry 3
        &#125;
    &#125;
&#125;

(2)启动/重启keepalived

systemctl restart keepalived

(2)使用keepalived配置Backup LVS
配置在备用机上

global_defs &#123;
    router_id keep_152 
&#125; 
vrrp_instance VI_1 &#123; 
    state  BACKUP
    interface ens33 
    virtual_router_id 41 
    priority 50 
    advert_int 1 
    authentication &#123; 
        auth_type PASS 
        auth_pass 1111 
    &#125; 
    virtual_ipaddress &#123; 
        192.168.1.150
    &#125;
&#125; 

#配置集群访问的ip+端口，端口和nginx保持一致
virtual_server 192.168.1.150 80&#123;
    #健康检查的时间，单位：秒
    delay_loop 6
    #配置负载均衡的算法，默认的轮询
    lb_algo rr
    #设置LVS的模式 NAT|TUN|DR
    lb-kind DR
    #设置会话持久化的时间
    persistence_timeout 5
    #协议
    protocol TCP
    
    #配置负载均衡的真实服务器，也就是nginx节点的具体的ip地址
    real_server 192.168.1.171 80&#123;
        #轮询权重配比
        weight 1
        #设置健康检查
        TCP_CHECK &#123;
            #检查80端口
            connect_port 80
            #超时时间
            connect_timeout 2
            #重试次数
            nb_get_retry 2
            #重试间隔时间
            delay_before_retry 3
        &#125;
    &#125;
    real_server 192.168.1.171 80&#123;
        weight 1
        TCP_CHECK &#123;
            connect_port 80
            connect_timeout 2
            nb_get_retry 2
            delay_before_retry 3
        &#125;
    &#125;
&#125;
</code></pre>

      </div>
      <div class="post-tags-categories">
        
      </div>
      
        <div class="copyright">
  <ul class="post-copyright">
    <li class="post-copyright-author">
    <strong>作者:  </strong>张存</a>
    </li>
    <li class="post-copyright-link">
    <strong>文章链接:  </strong>
    <a href="/2022/12/06/nginx-cong-an-zhuang-dao-gao-ke-yong-yi-pian-gao-ding/" target="_blank" title="Nginx 从安装到高可用，一篇搞定！">https://blog.zhangcun.store/2022/12/06/nginx-cong-an-zhuang-dao-gao-ke-yong-yi-pian-gao-ding/</a>
    </li>
    <li class="post-copyright-license">
      <strong>版权声明:   </strong>
      本网站所有文章除特别声明外,均采用 <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">CC BY-NC-ND 4.0</a>
      许可协议。转载请注明出处!
    </li>
  </ul>
<div>
      
    </article>
    <!-- 上一篇文章和下一篇文章 -->
    
      <!-- 文章详情页的上一页和下一页 -->
<div class="post-nav">



  
  <div class="post-nav-prev post-nav-item">
    <div class="post-nav-img lazyload" data-original="/medias/3.jpg" style="background-size: cover; 
      background-position: center center;">
    </div>
    <a href="/2022/12/06/yun-xing-cheng-xu-bao-gao-modulenotfounderror-no-module-named-cython-jie-jue-fang-fa/" class="post-nav-link">
      <div class="title">
        <i class="fa fa-angle-left"></i> 上一篇:
        <div class="title-text">运行程序报告 ModuleNotFoundError: No module named &#39;Cython&#39; 解决方法</div>
      </div>
      
      <!-- <div class="content">
        运行代码出现找不到Cython模块报错，如下：
安装升级下Cython可以解决:  pip3 install –upgr
      </div> -->
    </a>
  </div>



  
  <div class="post-nav-next post-nav-item">
    <div class="post-nav-img lazyload" data-original="/medias/13.jpg" style="background-size: cover; 
      background-position: center center;">
    </div>
    <a href="/2022/12/06/ru-he-cha-kan-dang-qian-docker-yi-deng-lu-yong-hu-de-yong-hu-ming-he-mi-ma/" class="post-nav-link">
      <div class="title">
        下一篇: <i class="fa fa-angle-right"></i>
        <div class="title-text">如何查看当前docker已登录用户的用户名和密码</div>
      </div>
      <!-- <div class="content">
         查看所有docker服务器和登录的用户密码：
cat /root/.docker/config.json

输出结果中
      </div> -->
    </a>
  </div>

</div>

    
    

    <!-- 打赏 -->
    
      <div id="appDonate" class="post-donate">
  <div id="donate_board" class="donate_bar center" ref="donate">
    <a id="btn_donate" class="btn_donate" href="javascript:;" title="打赏" @click="showDialogDrawer()"></a>
  </div>
  <transition name="fade">
    <div 
      class="donate-box-mask"
      v-cloak 
      v-if="visible"
      @click="cancelDialogDrawer()"
    >
    </div>
  </transition>
  <transition name="bounce">
    <div class="donate-box" v-cloak v-if="visible">
      <div class="donate-box_close">
        <i class="fa fa-times" aria-hidden="true" @click="cancelDialogDrawer" pointer></i>
      </div>
      <div class="donate-box_title">
        <h4>
          你的赏识是我前进的动力
        </h4>
      </div>
      <div class="donate-box_tab">
        <div class="Alipay" pointer :class="{'active': tabActive === 'Alipay'}" @click="changeTabActive('Alipay')">
          支付宝
        </div>
        <div class="WeChatpay" pointer :class="{'active': tabActive === 'WeChatpay'}" @click="changeTabActive('WeChatpay')">
          微信
        </div>
      </div>
      <div class="donate-box_img">
        <div class="AlipayImg" v-if="tabActive === 'Alipay'">
          <img src="/medias/zfb.jpg" alt="支付宝打赏" />
        </div> 
        <div class="WeChatpayImg" v-if="tabActive === 'WeChatpay'">
          <img src="/medias/wx.jpg" alt="微信打赏" />
        </div>
      </div>
    </div>
  </transition>
</div>

<script>
  var body = document.body || document.documentElement || window;
  var vm = new Vue({
    el: '#appDonate',
    data: {
      visible: false,
      tabActive: 'Alipay',
      top: 0,
    },
    computed: {
    },
    mounted() {
    },
    methods: {
      showDialogDrawer() {
        this.visible = true;
        // 防止页面滚动，只能让弹框滚动
        // function getScroll() {
        //   return {
        //     left: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0,
        //     top: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
        //   };
        // }
        this.top = $(document).scrollTop() // or getScroll().top
        // console.log('aa', $('.main-content'));
        body.style.cssText = 'overflow: hidden;';
      },
      cancelDialogDrawer() {
        this.visible = false;
        body.removeAttribute('style');
        $(document).scrollTop(this.top)
      },
      changeTabActive(name) {
        this.tabActive = name;
      }
    },
    created() {}
  })
</script>
    

    <!-- 分享 -->
    
      <!-- https://github.com/overtrue/share.js -->
<!-- 文章详情页的分享 -->
<div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>

<script src="/js/shareJs/social-share.min.js"></script>
</script>

<style>
  .social-share {
    margin: 20px 0;
  }
</style>


    
    
    <!-- 评论 -->
    <!-- 评论 -->

  <div id="myComment">
    
      <div id="gitment-container"></div>

    
  </div>

<!-- comment script in themes\hexo-theme-bamboo\layout\_partial\scripts\index.ejs -->


  </div>

  <!-- 目录 -->
  <!-- 文章详情页右侧目录 -->

  <div class="toc-aside">
    <div class="toc-main">
      <div class="toc-aside-title">
        <i class="fa fa-list-ul" aria-hidden="true"></i><span>本文目录</span>
        
          <div class="toc-open-close">本文目录</div>
        
      </div>
      <div class="toc-content">
        <div class="toc"></div>
      </div>
    </div>
  </div>
  <!-- js在scripts目录下的的toc.ejs里面 -->
  

  <script>
    function openBtnClickFn () {
      let openOrCloseBtn = $('.toc-aside .toc-aside-title .toc-open-close');
      let open = eval('' || 'true');
      openOrCloseBtn.click(function() {
        if (open === true) {
          $(".toc-aside").css({'width': 0, 'padding': 0});
          $(".toc-content").css({'width': 0});
          $(".toc-aside-title span, .toc-aside-title i").css({'display': 'none'});
          $(".main-content").css({'width': '75%', 'margin': '10px auto'});
          open = false;
        } else {
          $(".toc-aside").css({'width': '300px', 'padding': '0 10px'});
          $(".toc-content").css({'width': '300px'});
          $(".toc-aside-title span, .toc-aside-title i").css({'display': 'inline-block'});
          $(".main-content").css({'width': '65%', 'margin-right': '10px', 'margin-left': 'calc(35% - 350px)'});
          open = true;
        }
      });
    };
    openBtnClickFn();
    document.addEventListener('pjax:complete', function () {
      openBtnClickFn();
    })
  </script>


  

  <!-- 图片放大 Wrap images with fancybox support -->
  <script src="/js/wrapImage.js"></script>
</div>

<!-- 文章详情页背景图 -->
<div id="appBgSwiper" style="position: fixed;left: 0;top: 0;width: 100%;height: 100%;z-index: -2;" :style="{'background-color': bgColor ? bgColor : 'transparent'}">
    <transition-group tag="ul" :name="names">
        <li v-for='(image,index) in img' :key='index' v-show="index === mark" class="bg-swiper-box">
            <img :src="image" class="bg-swiper-img">
        </li>
    </transition-group>
</div>
<script>
    var vm = new Vue({
        el: '#appBgSwiper',
        data: {
            names: '' || 'fade' || 'fade', // translate-fade fade
            mark: 0,
            img: [],
            bgColor: '',
            time: null
        },
        methods: {   //添加方法
            change(i, m) {
                if (i > m) {
                    // this.names = 'fade';
                } else if (i < m) {
                    // this.names = 'fade';
                } else {
                    return;
                }
                this.mark = i;
            },
            prev() {
                // this.names = 'fade';
                this.mark--;
                if (this.mark === -1) {
                    this.mark = 3;
                    return
                }
            },
            next() {
                // this.names = 'fade';
                this.mark++;
                if (this.mark === this.img.length) {
                    this.mark = 0;
                    return
                }
            },
            autoPlay() {
                // this.names = 'fade';
                this.mark++;
                if (this.mark === this.img.length) {
                    this.mark = 0;
                    return
                }
            },
            play() {
                let bgImgDelay = '' || '180000'
                let delay = parseInt(bgImgDelay) || 180000;
                this.time = setInterval(this.autoPlay, delay);
            },
            enter() {
                clearInterval(this.time);
            },
            leave() {
                this.play();
            }
        },
        created() {
            this.play()
        },
        beforeDestroy() {
            clearInterval(this.time);
        },
        mounted() {
            let prop = ''|| '';
            let isImg = prop.includes('.bmp') || prop.includes('.jpg') || prop.includes('.png') || prop.includes('.tif') || prop.includes('.gif') || prop.includes('.pcx') || prop.includes('.tga') || prop.includes('.exif') || prop.includes('.fpx') || prop.includes('.psd') || prop.includes('.cdr') || prop.includes('.pcd') || prop.includes('.dxf') || prop.includes('.ufo') || prop.includes('.eps') || prop.includes('.ai') || prop.includes('.raw') || prop.includes('.WMF') || prop.includes('.webp') || prop.includes('.jpeg') || prop.includes('http://') || prop.includes('https://') 
            if (isImg) {
                let img = prop.split(',');
                let configRoot = '/'
                let arrImg = [];
                img.forEach(el => {
                    var Expression=/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
			        var objExp = new RegExp(Expression);

                    if(objExp.test(el)) {
                        // http or https
                        arrImg.push(el);
                    } else {
                        // 非http or https开头
                        // 本地文件
                        let firstStr = el.charAt(0);
                        if (firstStr == '/') {
                            el = el.substr(1); // 删除第一个字符 '/',因为 configRoot最后一个字符为 /
                        }
                        el = configRoot + el;
                        arrImg.push(el);
                    }
                })
                this.img = arrImg;
            } else {
                this.bgColor = prop;
            }
        }
    })
</script>

<style>
    .bg-swiper-box {
        position: absolute;
        display: block;
        width: 100%;
        height: 100%;
    }
    .bg-swiper-img {
        object-fit: cover;
        width: 100%;
        height: 100%;
    }
</style>

      </main>
    </div>

    <!-- 页脚 -->
    
  
  <div class="footer bg-color">
    <div class="footer-main">
      
        
          <div class="link">
            
              
                <a href="/atom.xml" class="social">
                  
                    <i class="fa fa-rss" aria-hidden="true"></i>
                  
                </a>
              
            
              
                <a href="mailto:1776803208@qq.com" class="social">
                  
                    <i class="fa fa-envelope" aria-hidden="true"></i>
                  
                </a>
              
            
              
                <a target="_blank" rel="noopener" href="https://github.com/zhangcun1113/hexo-theme-bamboo" class="social">
                  
                    <i class="fa fa-github" aria-hidden="true"></i>
                  
                </a>
              
            
              
                <a href="tencent://AddContact/?fromId=50&amp;fromSubId=1&amp;subcmd=all&amp;uin=1730241541" class="social">
                  
                    <i class="fa fa-qq" aria-hidden="true"></i>
                  
                </a>
              
            
          </div>
        
      
        
          <div class="footer-copyright">
            <p>Copyright © 2001 - 2023 <a href="https://blog.zhangcun.store">zhangcun</a> </p>

          </div>
        
      
        
          
            <!-- 不蒜子统计 -->
            <!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
      <i class="fa fa-eye" aria-hidden="true"></i>本站总访问量：<span id="busuanzi_value_site_pv"></span> 次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
      <i class="fa fa-users" aria-hidden="true"></i>本站访客数：<span id="busuanzi_value_site_uv"></span> 人
</span>

          
        
      
        
          <div class="footer-custom">
            
          </div>
        
      
    </div>
  </div>



    <!-- 渲染暗黑按钮 -->
    
      <div class="dark">
  <div class="dark-content">
    <i class="fa fa-moon-o" aria-hidden="true"></i>
    <!-- <span>关灯</span> -->
  </div>
  
</div>

<script>
  $(function() {
    let isDark = JSON.parse(localStorage.getItem('dark'))  || JSON.parse('false');
    if (isDark) {
      $(".dark-content").replaceWith(
          `
          <div class='dark-content'>
            <i class="fa fa-lightbulb-o" aria-hidden="true"></i>
          </div>
          `
        );
    }
    $('.dark').click(function() {
      if ($(document.body).is('.darkModel')) {
        $(document.body).removeClass('darkModel');
        localStorage.setItem('dark', false);
        $(".dark-content").replaceWith(
          `
          <div class='dark-content'>
            <i class="fa fa-moon-o" aria-hidden="true"></i>
          </div>
          `
        );
      } else {
        $(document.body).addClass('darkModel');
        localStorage.setItem('dark', true);
        $(".dark-content").replaceWith(
          `
          <div class='dark-content'>
            <i class="fa fa-lightbulb-o" aria-hidden="true"></i>
          </div>
          `
        );
      }
    })
  })
</script>
    
    <!-- 渲染回到顶部按钮 -->
    
      <div class="goTop top-btn-color" pointer>
  <i class="fa fa-arrow-up" aria-hidden="true"></i>
</div>
<script src="/js/goTop.js"></script>
    
    <!-- 渲染左下角音乐播放器 -->
    
      <link rel="stylesheet" href="/js/aplayer/APlayer@1.10.1.min.css">
<style>
.aplayer .aplayer-lrc p {
  
  font-size: 12px;
  font-weight: 700;
  line-height: 16px !important;
}

.aplayer .aplayer-lrc p.aplayer-lrc-current {
  
  font-size: 15px;
  color: #22b1eb;
}


.aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
  left: -66px !important;
}

.aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
  left: 0px !important;
}


</style>
<meting-js  
  class=""
  server="netease"
  type="playlist"
  id="8444991407"
  fixed='true'
  autoplay='true'
  theme='#22b1eb'
  loop='all'
  order='random'
  preload='auto'
  volume='0.7'
  list-folded='true'
>
</meting-js>

<!-- <style>
  #aplayer {
    position: fixed;
    left: 0;
    bottom: 300px;
  }
</style> -->
<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>
    

    <!-- 图片放大 -->
    
      <script src="/js/fancybox/jquery.fancybox.min.js"></script>
    

    <!-- 百度解析 -->
    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <!-- 背景彩带 -->
    
    
    <script src="/js/app.js" data-pjax></script>
    
    <!-- 文章目录所需js -->
<link href="/js/tocbot/tocbot.css" rel="stylesheet">
<script src="/js/tocbot/tocbot.min.js"></script>

<script>
  var headerEl = 'h2, h3, h4',  //headers 
      content = '.post-detail',//文章容器
      idArr = {};  //标题数组以确定是否增加索引id
      //add #id
  var option = {
    // Where to render the table of contents.
    tocSelector: '.toc',
    // Where to grab the headings to build the table of contents.
    contentSelector: content,
    // Which headings to grab inside of the contentSelector element.
    headingSelector: headerEl,
    scrollSmooth: true,
    scrollSmoothOffset: -80,
    headingsOffset: -($(window).height() * 0.4 - 45),
    positionFixedSelector: '.toc-main',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto',
  }
  if ($('.toc').length > 0) {

    $(content).children(headerEl).each(function () {
      //去除空格以及多余标点
      var headerId = $(this).text().replace(/[\s|\~|`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\_|\+|\=|\||\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?|\：|\，|\。]/g, '');

      headerId = headerId.toLowerCase();
      if (idArr[headerId]) {
        //id已经存在
        $(this).attr('id', headerId + '-' + idArr[headerId]);
        idArr[headerId]++;
      }
      else {
        //id未存在
        idArr[headerId] = 1;
        $(this).attr('id', headerId);
      }
    });

    tocbot.init(option);
    
  }


  document.addEventListener('pjax:send', function () {
    if ($('.toc').length) {
      tocbot.destroy();
    }
  });

  document.addEventListener('pjax:complete', function () {
    if ($('.toc').length) {
      tocbot.init(option);
    }
  });

  
</script>

<style>
.is-position-fixed {
  position:sticky !important;
  top: 74px;
}
.toc-main ul {
  counter-reset: show-list;
}
.toc-main ul li::before {
  content: counter(item)".";
  display: block;
  position: absolute;
  left: 12px;
  top:0;
}
/* .toc > .toc-list {
  padding-left: 35px;
}
.toc>.toc-list li {
  list-style: decimal;
}
.toc-list {
  padding-left: 25px;
} */
</style> 

<!-- 渲染issues标签里的内容 -->
<script>
  function loadIssuesJS() {
    if ($(".post-detail").find(".issues-api").length == 0) {
      return;
    } 
    loadScript('/js/issues/index.js');
  };
  $(function () {
    loadIssuesJS();
  });
  document.addEventListener('pjax:complete', function () {
    if (typeof IssuesAPI == "undefined") {
      loadIssuesJS();
    }
  })
</script>

<!-- 输入框打字特效 -->
<!-- 输入框打字特效 -->

  <script src="/js/activate-power-mode.js"></script>
  <script>
    POWERMODE.colorful = true;  // 打开随机颜色特效
    POWERMODE.shake = false;    // 关闭输入框抖动
    document.body.addEventListener('input', POWERMODE);//监听打字事件
  </script>


<!-- markdown代码一键复制功能 -->

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/v-plugs-ayu/lib/ayu.css">
  <script src="https://cdn.jsdelivr.net/npm/v-plugs-ayu/lib/ayu.umd.min.js"></script>
  <script src="/js/clipboard/clipboard.min.js"></script>
  <div id="appCopy">
  </div>
  <script data-pjax>
    var vm = new Vue({
      el: '#appCopy',
      data: {
      },
      computed: {
      },
      mounted() {
        const that = this;
        var copy = '复制';
        /* code */
        var initCopyCode = function () {
          var copyHtml = '';
          copyHtml += '<button class="btn-copy" data-clipboard-snippet="" style="position:absolute;top:0;right:0;z-index:1;">';
          copyHtml += '<i class="fa fa-copy"></i><span>' + copy + '</span>';
          copyHtml += '</button>';
          $(".post-detail pre").not('.gutter pre').wrap("<div class='codeBox' style='position:relative;width:100%;'></div>")
          $(".post-detail pre").not('.gutter pre').before(copyHtml);
          new ClipboardJS('.btn-copy', {
            target: function (trigger) {
              return trigger.nextElementSibling;
            }
          });
        }
        initCopyCode();
        $('.btn-copy').unbind('click').bind('click', function () {
          doSomething();
        })
        $(document).unbind('keypress').bind('keypress', function (e) {
          if (e.ctrlKey && e.keyCode == 67) {
            doSomething();
            // 返回false, 防止重复触发copy事件  
            // return false;
          }
        })
        //  监听 ctrl + c事件  
        // $(document).unbind('keypress').bind('keypress', function (e) {
        //   if (e.ctrlKey && e.keyCode == 67) {
        //     doSomething();
        //     // 返回false, 防止重复触发copy事件  
        //     return false;
        //   }
        // })

        // // 鼠标右键的复制事件  
        // $(document).unbind('copy').bind('copy', function (e) {
        //   doSomething();
        // });

        function doSomething() {
          that.$notify({
            title: "成功",
            content: "代码已复制，请遵守相关授权协议。",
            type: 'success'
          })
        }
      },
      methods: {
      },
      created() { }
    })
  </script>


<!-- 图片懒加载 -->
<script src="/js/lazyload/lazyload@1.9.1.js"></script>
<script data-pjax>
  $(function () {
    $("div.lazyload, img.lazyload, a.lazyload").lazyload(
      {
        effect: "show",
        placeholder: "https://img10.360buyimg.com/ddimg/jfs/t1/159345/8/2271/222193/5ff7b36fEe49f5663/a95287c20385127f.gif"    //图片未加载出来时显示的占位图
      }
    );
  });
</script>

<!-- 卡片滚动动画 -->
   

<!-- 评论所需js -->

    
        <script type="text/javascript">
    var bamboo = {};
    bamboo.utterance = {};
    
    function check_utterance() {
        let isDark = JSON.parse(localStorage.getItem('dark'))  || JSON.parse('false');
        if (isDark) {
            bamboo.utterance.Theme = 'github-dark';
        } else {
            bamboo.utterance.Theme = 'github-light';
        }

        return document.getElementById("gitment-container");
    }
    comment_el = '#gitment-container';
    load_utterance = function () {
        if ($(comment_el).length) {
            // 匿名函数，防止污染全局变量
            const HEAD = check_utterance();
            
            var utterances = document.createElement('script');
            utterances.type = 'text/javascript';
            utterances.async = true;
            utterances.setAttribute('issue-term','pathname')
            utterances.setAttribute('theme', bamboo.utterance.Theme)
            utterances.setAttribute('repo','')
            utterances.crossorigin = 'anonymous';
            utterances.src = 'https://utteranc.es/client.js';
            // content 是要插入评论的地方
            document.getElementById('gitment-container').appendChild(utterances);
            
        }
    }

    function dark_utterance() {
        const HEAD = check_utterance();
        if (!HEAD) return;
        const message = {
            type: 'set-theme',
            theme: bamboo.utterance.Theme
        };
        const utteranceIframe = document.querySelector('iframe');
        utteranceIframe.contentWindow.postMessage(message, 'https://utteranc.es');
    }

    $(document).ready(load_utterance);
    document.addEventListener('pjax:complete', function () {
        load_utterance();
    });

    $('.dark').click(function() {
        setTimeout(() => {
            dark_utterance();
        });
    })
    
</script>

<style>
    .utterances {
        max-width: inherit!important;
    }
</style>
    


<!-- 鼠标点击特效 -->
<!-- 爱心点击 -->

	
		<canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 999; pointer-events: none;" ></canvas>
		<script src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script>
		<script src="/js/cursor/explosion.min.js"></script>
	




    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" data-pjax></script>


    <!-- pjax -->
    

<!-- pjax -->


  <script src="/js/pjax@0.2.8/index.js"></script>
  
    <!-- 样式位于：source/css/_third-party/pjaxanimate.styl -->

<div class="pjax-animate">
  
    <div class="loading-circle"><div id="loader-circle"></div></div>
    <script>
      window.ShowLoading = function() {
        $(".loading-circle").css("display", "block");
      };
      window.HideLoading = function() {
        $(".loading-circle").css("display", "none");
      }
    </script>
  
	<script>
    document.addEventListener('pjax:complete', function () {
      window.HideLoading();
    })
    document.addEventListener('pjax:send', function () {
      window.ShowLoading();
    })
    document.addEventListener('pjax:error', function () {
      window.HideLoading();
    })
	</script>
</div>

  

  <script>
    var pjax = new Pjax({
      elements: 'a[href]:not([href^="#"]):not([href="javascript:void(0)"]):not([no-pjax])',   // 拦截正常带链接的 a 标签
      selectors: ["#pjax-container","title"],                                   // 根据实际需要确认重载区域
      cacheBust: false,   // url 地址追加时间戳，用以避免浏览器缓存
      timeout: 5000
    });

    document.addEventListener('pjax:send', function (e) {

      try {
        var currentUrl = window.location.pathname;
        var targetUrl = e.triggerElement.href;
        var banUrl = [""];
        if (banUrl[0] != "") {
          banUrl.forEach(item => {
            if(currentUrl.indexOf(item) != -1 || targetUrl.indexOf(item) != -1) {
              window.location.href = targetUrl;
            }
          });
        }
      } catch (error) {}

      $(window).unbind('resize');
      $(window).unbind('scroll');
      $(document).unbind('scroll');
      $(document).unbind('click');
      $('body').unbind('click');

    })
    
    document.addEventListener('pjax:complete', function () {
      $('script[data-pjax], .pjax-reload script').each(function () {
        $(this).parent().append($(this).remove());
      });
    });

    document.addEventListener('pjax:error', function (e) {
      window.location.href = e.triggerElement.href;
    })
    
    // 刷新不从顶部开始
    document.addEventListener("DOMContentLoaded", function () {
      history.scrollRestoration = 'auto';
    })
  </script>



  </body>
</html>